import { Button, Form, Input } from "antd";
import alert from "../../utils/alert";
import client from '../../utils/client';

export default function Page() {
  const [form] = Form.useForm();

  function onOk() {
    form.validateFields().then(values => {
      client.change_password(values.当前密码, values.新的密码)
        .then(d => d ? alert('修改成功') : alert('修改失败,请确认当前密码是否正确'));
    }).catch(e => null);
  }
  return (
    <div style={{ padding: 20 }}>
      <Form form={form} onFinish={onOk} style={{ width: 300, display: 'flex', flexDirection: 'column' }}>
        <Form.Item name="当前密码" label="当前密码" rules={[{ required: true }]}><Input.Password /></Form.Item>
        <Form.Item name="新的密码" label="新的密码" rules={[{
          required: true,
          validator: (_, value) => {
            if (!value) return Promise.reject(Error('请输入新的密码'));
            let n = 0;
            if (value.length < 8) {
              return Promise.reject(Error('密码长度不少于8位'));
            }
            if (value.match(/([a-z])+/)) n++;
            if (value.match(/([0-9])+/)) n++;
            if (value.match(/([A-Z])+/)) n++;
            if (value.match(/[^a-zA-Z0-9]+/)) n++;
            if (n < 3) {
              return Promise.reject(Error('至少包含大写字母, 小写字母, 数字和特殊字符中的三种'));
            }
            return Promise.resolve();
          }
        }]}><Input.Password /></Form.Item>
        <Form.Item name="确认密码" label="确认密码" dependencies={['新的密码']} rules={[{
          required: true,
          validator: (_, value) => {
            if (!value) return Promise.reject(Error('请输入确认密码'));
            return value === form.getFieldValue('新的密码') ? Promise.resolve() : Promise.reject(Error('确认密码不匹配'));
          }
        }]}><Input.Password /></Form.Item>
        <Button type="primary" htmlType="submit">确定</Button>
      </Form>
    </div>
  );
}